package struct.advanced.heap;

import struct.primary.array.Array;

/**
 * @author MAX
 * @version 1.0
 * @description 高级数据结构-最大堆
 * @date 2022/1/22 16:14
 */
public class MaxHeap<E extends Comparable<E>> {
    private Array<E> data;

    public MaxHeap() {
        data = new Array<>();
    }

    public MaxHeap(int capacity) {
        data = new Array<>(capacity);
    }

    public MaxHeap(E[] arr) {
        data = new Array<>(arr);
        for (int i = parent(arr.length - 1); i >= 0; i--) {
            siftDown(i);
        }
    }

    public int size() {
        return data.size();
    }

    public boolean isEmpty() {
        return data.isEmpty();
    }

    public void add(E e) {
        data.addLast(e);
        siftUp(data.size() - 1);
    }

    public E extractMax() {
        if (isEmpty()) throw new RuntimeException("Heap Empty");
        E max = findMax();
        data.swap(0, data.size() - 1);
        data.removeLast();
        siftDown(0);
        return max;
    }

    public E replace(E e) {
        E ret = data.get(0);
        data.set(0, e);
        siftDown(0);

        return ret;
    }

    public E findMax() {
        if(isEmpty()) throw new RuntimeException("Heap Empty");
        return data.get(0);
    }

    private void siftDown(int index) {
        while (leftChild(index) < data.size()) {
            int j = leftChild(index);
            if (j + 1 < data.size() && data.get(j + 1).compareTo(data.get(j)) > 0) {
                j = rightChild(index);
            }

            if(data.get(index).compareTo(data.get(j)) >= 0) break;
            data.swap(index, j);
            index = j;
        }
    }

    private void siftUp(int index) {
        while (index > 0 && data.get(parent(index)).compareTo(data.get(index)) < 0) {
            data.swap(parent(index), index);
            index = parent(index);
        }
    }

    private int parent(int index) {
        if (index == 0) throw new IllegalArgumentException("index-0 doesn't have parent.");
        return (index - 1) / 2;
    }

    private int leftChild(int index) {
        return (2 * index) + 1;
    }

    private int rightChild(int index) {
        return (2 * index) + 2;
    }

}
